package com.project.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.project.bean.LessonBean;
import com.project.dao.LessonMapper;
import com.project.service.ILessonService;

@Service(value = "lessonService")
public class LessonServiceImpl implements ILessonService{
	@Autowired
	private LessonMapper lessonMapper;



	@Override
	public List<LessonBean> showLessons(int lUId) {
		//取当前日期
		Calendar cal = Calendar.getInstance();
		//取当前日期后的第六天
		Calendar cal6 = Calendar.getInstance();
		cal6.set(Calendar.DATE,cal6.get(Calendar.DATE)+6);
		Date date = cal.getTime();
		Date date1 = cal6.getTime();
		//计算七天内的课程数
		int count = lessonMapper.countLessonByDate(lUId,date, date1);
		//课程的总天数
		int days = count/3;
		if(days==7) {
		//如果7天内都有课程，则全部显示
			return lessonMapper.selectByLUId(lUId,date, date1);
		}else {
		//如果7天内有几天没有课程，则先添加再显示
			//取当前星期数
			int weekDay = cal.get(Calendar.DAY_OF_WEEK)-1;
			if(weekDay==0) {
				weekDay=7;
			}
			//添加课程的集合
			List<LessonBean> list = new ArrayList<LessonBean>();
			//获取这一天前一天的日期
			cal.set(Calendar.DATE,cal.get(Calendar.DATE)+days-1);
			//从哪一天开始添加课程
			for (int startDay= days; startDay < 7; startDay++) {
				//获取这一天的日期
				cal.set(Calendar.DATE,cal.get(Calendar.DATE)+1);
				Date addDate = cal.getTime();
				//获取这一天是星期几
				int weekday = (weekDay+startDay>7)?weekDay+startDay-7:weekDay+startDay;
				//默认为不可预约
				int lState = 3;
				//添加这一天早中晚（1,2,3）的课程
				for (int i = 1; i < 4; i++) {
					LessonBean lesson = new LessonBean();
					lesson.setlPrice(0.0);
					lesson.setlDate(addDate);
					lesson.setlTime(i);
					lesson.setlUId(lUId);
					lesson.setlState(lState);
					lesson.setlDay(weekday);
					list.add(lesson);
				}
			}
			lessonMapper.insertBatchSelective(list);
			return lessonMapper.selectByLUId(lUId,date, date1);
		}
	}



	@Override
	public LessonBean findLessonById(int lId) {	
		return lessonMapper.selectByPrimaryKey(lId);
	}



	@Override
	public int updateLesson(int lId, double lPrice, int lState) {
		LessonBean lesson = new LessonBean();
		lesson.setlId(lId);
		lesson.setlPrice(lPrice);
		lesson.setlState(lState);
		return lessonMapper.updateByPrimaryKeySelective(lesson);
	}

}
